//
//  MyOrderViewController.swift
//  iModern
//
//  Created by Ralf on 6/1/15.
//  Copyright (c) 2015 com.starlooking. All rights reserved.
//

import UIKit

class MyOrderViewController: TableViewController
{
    var max            = 0
    var offset         = 0
    var end            = false
    var appDelegate    = UIApplication.sharedApplication().delegate as! AppDelegate
    let articleManager = ArticleManager()
    var articles       = NSMutableArray()

    var segmentedControl: UISegmentedControl?

    override func viewDidLoad()
    {
        super.viewDidLoad()
        self.navigationItem.title = "我的订单"

        self.tableView.registerNib(UINib(nibName: "MyOrderViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "ORDER")
        self.tableView.registerNib(UINib(nibName: "MyOrderCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "MORDER")
        self.tableView.registerNib(UINib(nibName: "ChooseCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "CHOOSE")

        let view1 = UIView()
        view1.frame = CGRectMake(0, 10, 180, 50)
        view1.backgroundColor = UIColor.groupTableViewBackgroundColor()
        self.tableView!.tableHeaderView = view1

        let screen = UIScreen.mainScreen().bounds
        segmentedControl = UISegmentedControl(items: ["未评价", "已评价"])
        segmentedControl!.tintColor = UIColor(red: 0.40784313725490196, green: 0.6588235294117647, blue: 0.19215686274509805, alpha: 1)
        segmentedControl?.frame = CGRectMake((screen.size.width - 180) / 2, 10, 180, 28)
        segmentedControl!.selectedSegmentIndex = 0
        segmentedControl!.addTarget(self, action: "segmentSelected:", forControlEvents: .ValueChanged)
        view1.addSubview(segmentedControl!)

        self.view.backgroundColor = UIColor.groupTableViewBackgroundColor()
        
        self.loadData()
        initBackButton()
    }

    override func viewWillAppear(animated: Bool)
    {
    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return articles.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let order = articles[indexPath.row] as! NSMutableDictionary
        let cell  = tableView.dequeueReusableCellWithIdentifier("MORDER", forIndexPath: indexPath) as! MyOrderCell
        cell.selectionStyle = UITableViewCellSelectionStyle.None
        cell.setData(order)
        return cell
    }

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
    {
        return 140
    }

    func loadData()
    {
        if (end)
        {
            return; }

        if (appDelegate.isLogged())
        {
            var rs: ResultSet?
            //let userName = appDelegate.contactManager.contact["userName"] as! String
            if self.segmentedControl!.selectedSegmentIndex == 0
            {
                rs = articleManager.queryMyAppointment(max, offset: offset, reviewed: false)
            }
            else
            {
                rs = articleManager.queryMyAppointment(max, offset: offset, reviewed: true)
            }
            if (self.verifyResutSet(rs))
            {
                if (rs!.isEmpty())
                {
                    end = true
                }
                else
                {
                    articles.addObjectsFromArray(rs!.toMutableArray() as [AnyObject])
                    offset = articles.count
                }
            }
        }
        self.tableView.reloadData()
    }

    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        let article    = articles[indexPath.row] as! NSMutableDictionary
        let controller = MyOrderformFormViewCellViewController()
        controller.order = article as [NSObject:AnyObject]
        self.pushViewController(controller)
    }

    @IBAction override func reloadData(sender: AnyObject?)
    {
        offset = 0
        end = false
        articles.removeAllObjects()
        self.loadData()
        super.reloadData(sender)
    }

    func segmentSelected(sender: UISegmentedControl)
    {
        reloadData(sender)
    }

}
